namespace _8 {

var myAtoi = function(str: string): number {
    str = str.trim()
    let sign = 1
    if (str.startsWith('-')) {
        sign = -1
        str = str.substr(1) 
    }
    else if (str.startsWith('+')) str = str.substr(1) 

    if (!str) return 0
    let answer = 0;
    const zero = '0'.charCodeAt(0)
    for(var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) < zero || str.charCodeAt(i) > zero + 9) break
        answer = answer * 10 + sign*(str.charCodeAt(i) - zero)
        if (answer > Math.pow(2, 32) / 2 - 1) return (Math.pow(2, 32) / 2 - 1)
        if (answer < -Math.pow(2, 32) / 2) return -Math.pow(2, 32) / 2
    }
    return answer * sign
}

console.assert( myAtoi( '12') === 12)

}